package com.qianfeng.android.baoman.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.BitmapHelp;
import com.qianfeng.android.baoman.R;
import com.qianfeng.android.baoman.model.DownBooks;
import com.qianfeng.android.baoman.task.MyInterface;
import com.qianfeng.android.baoman.task.ZipDownloadTask;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * Created by ldy on 2015/3/15.
 */
public class FindDownLoadBookAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private List<DownBooks> downBookses;
    private Context context;
    private String zip_url;
    private String name;

    public FindDownLoadBookAdapter(Context context, List<DownBooks> downBookses) {
        if (context != null) {
            inflater = LayoutInflater.from(context);
        } else {
            throw new IllegalArgumentException("Context must be not null");
        }
        this.context = context;
        this.downBookses = downBookses;
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (downBookses != null) {
            ret = downBookses.size();
        }
        return ret;
    }

    @Override
    public Object getItem(int i) {
        Object ret = null;
        if (downBookses != null) {
            ret = downBookses.get(i);
        }
        return ret;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        if (convertView != null) {
            ret = convertView;
        } else {
            ret = inflater.inflate(R.layout.item_down_load_book, parent, false);
        }

        ViewHolder holder = (ViewHolder) ret.getTag();
        if (holder == null) {
            holder = new ViewHolder();
            holder.cartoonIcon = (ImageView) ret.findViewById(R.id.find_download_cartoon_icon);
            holder.downBtn = (ImageView) ret.findViewById(R.id.find_download_cartoon_btn);
            holder.zanImg = (ImageView) ret.findViewById(R.id.find_download_zan_img);
            holder.dateTxt = (TextView) ret.findViewById(R.id.find_download_time_txt);
            holder.cProgressbar = (ProgressBar) ret.findViewById(R.id.item_download_progress);

            ret.setTag(holder);
        }
        holder.downBtn.setTag(position);
        final ProgressBar myProgressbar = holder.cProgressbar;

        DownBooks downBook = downBookses.get(position);
        int imgSwitch = downBook.getImgSwitch();
        if (imgSwitch == 0) {
            imgSwitch = R.drawable.bookshop_down_load_btn;
        } else {
            imgSwitch = R.drawable.bookshop_has_down_load_btn;
        }
        holder.downBtn.setImageResource(imgSwitch);
        //下载地址
        zip_url = downBook.getZip_url();

        name = downBook.getName();

        //显示日期
        String date = downBook.getDate();
        holder.dateTxt.setText(date);

        //显示图书的封面
        holder.cartoonIcon.setImageResource(R.drawable.clean_default);
        String bookIcon = downBook.getIcon();
        holder.cartoonIcon.setTag(bookIcon);

        BitmapHelp.getUtils().display(holder.cartoonIcon, downBook.getIcon(), new BitmapLoadCallBack<ImageView>() {
            @Override
            public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                imageView.setImageBitmap(bitmap);
            }

            @Override
            public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

            }
        });

        holder.downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Object tag = v.getTag();
                if (tag instanceof Integer) {
                    int p = (Integer) tag;
                    final DownBooks book = downBookses.get(p);
                    notifyDataSetChanged();
                    String zipUrl = book.getZip_url();
                    String bookName = book.getName();
                    ZipDownloadTask zipDownloadTask = new ZipDownloadTask(new MyInterface() {

                        @Override
                        public void backResult() {
                            book.setImgSwitch(1);
                            notifyDataSetChanged();
                        }
                    }, myProgressbar);
                    zipDownloadTask.execute(zipUrl, bookName);
                }
            }
        });

        return ret;
    }

    private static class ViewHolder {
        private ImageView cartoonIcon;  //图书的封面
        private TextView dateTxt;   //日期
        private ImageView downBtn;   //下载按钮
        private ImageView zanImg;   //评分图片
        //进度条
        private ProgressBar cProgressbar;
    }


    public static void upZipFile(File zipFile, String folderPath)
            throws ZipException, IOException {
        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            desDir.mkdirs();
        }
        ZipFile zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            InputStream in = zf.getInputStream(entry);
            String str = folderPath;
            File desFile = new File(str, java.net.URLEncoder.encode(
                    entry.getName(), "UTF-8"));

            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
            }

            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[1024 * 1024];
            int realLength = in.read(buffer);
            while (realLength != -1) {
                out.write(buffer, 0, realLength);
                realLength = in.read(buffer);
            }

            out.close();
            in.close();

        }
    }


//    public static int unzipFile(File f){
//        int ret = -1;
//        if (f != null) {
//            if(f.exists() && f.canRead()){
//                try {
//                    ZipFile zip = new ZipFile(f);
//                    // TODO 看看如何获取 Zip 里面的文件如何获取
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return ret;
//    }
}
